package geektime.io.nio;

import java.util.Scanner;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 模拟客户端
 */
public class EchoClient {

    private static SocketChannel clientSocketChannel;
    private static ByteBuffer buffer;
    private static EchoClient echoClient;

    // 这里采用单例模式，所以需要将构造方法私有化
    private EchoClient() {
        try {
            clientSocketChannel = SocketChannel.open(new InetSocketAddress("localhost", 1234));
            buffer = ByteBuffer.allocate(256);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static EchoClient getInstance() {
        if (echoClient == null) {
            echoClient = new EchoClient();
        }
        return echoClient;
    }

    public void stop() {
        if (clientSocketChannel != null) {
            try {
                clientSocketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        // 创建EchoClient的实例
        EchoClient client = getInstance();
        // 发送单条信息
//        sendSingleMessage(client);
        // 发送多条信息
        sendMultipleMessage(client);
    }

//    private static void sendSingleMessage(EchoClient client) {
//        sendMessageToServer("hello");
//        client.stop();
//    }

    private static void sendMultipleMessage(EchoClient client) {
        Scanner scanner = new Scanner(System.in);
        String message;
        while (true) {
            message = scanner.nextLine();
            if ("exit".equals(message)) {
                break;
            }
            sendMessageToServer(message);
        }
        client.stop();
    }

    private static String sendMessageToServer(String message) {
        String response = null;
        try {
            // 将message内容放置到buffer中，然后写入到clientSocketChannel。记住：write前需要flip()
            buffer.put(message.getBytes());
            buffer.flip();
            clientSocketChannel.write(buffer);
            // 将buffer重置，并接收服务端返回的信息
            buffer.clear();
            clientSocketChannel.read(buffer);
            response = getCurrentTimesMessage(buffer);
            System.out.println("get the response: " + response);
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static String getCurrentTimesMessage(ByteBuffer buffer) {
        byte[] bytes = new byte[buffer.position()];
        buffer.flip();
        int i = 0;
        while (buffer.hasRemaining()) {
            bytes[i++] = buffer.get();
        }
        return new String(bytes);
    }


}
